<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/8/3
 * Time: 16:55
 */
class LoginLogQueen extends StatsLogBase
{
    public $queenName = 'loginLog';
    public $baseTableName = 'login_log';
    public $dbName = 'login_log';

    /**
     * 推入队列
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function push($data)
    {
        return parent::pushQueen($data, 'push_login_log_error', 'user_stats');
    }

    /**
     * 保存到数据库
     * @param $data
     * @return array
     */
    public function saveLog($data)
    {
        /**
         * 检测分库
         */
        $result = $this->checkDatabase();
        if (!$result) {
            $this->e('cannot_select_database');
            return false;
        }

        /**
         * 检查表是否存在
         */
        if (!$this->checkTableExists()) {
            return [];
        }

        /**
         * 保存日志数据
         */
        $data = [
            'uid'        => $data['uid'],
            'loginTime'  => $data['loginTime'],
            'platform'   => (int)$data['platform'],
            'channelID'  => empty($data['channelID'])? 0:$data['channelID'],
            'ver'        => empty($data['ver'])?'':$data['ver'],
            'createTime' => time()
        ];

        $result = $this->mysql->insert($this->tableName, $data);
        if (!$result) {
            $this->e('save_error', $this->mysql->error());
            $this->e('用户登录日志保存失败', $data);
            return [];
        }

        return $data;
    }

    /**
     *
     * @param $tableName
     * @return string
     */
    public function getCreateTableSql($tableName)
    {
        $sql = "CREATE TABLE `{$tableName}` (
              `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
              `uid` INT(11) UNSIGNED NOT NULL,
              `loginTime` INT(11) UNSIGNED NOT NULL DEFAULT 0,
              `platform` TINYINT(1) NOT NULL DEFAULT 0,
              `channelID` INT(11) UNSIGNED NOT NULL DEFAULT 0,
              `ver` VARCHAR(30) NOT NULL DEFAULT '',
              `createTime` INT(11) NOT NULL DEFAULT 0,
              PRIMARY KEY (`id`),
              KEY `uid` (`uid`),
              KEY `loginTime` (`loginTime`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='用户登录日志表'";

        return $sql;
    }
}